package com.touringapp.android.activity;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

public class Location implements Serializable {
	private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1505138221441507618L;
	
	private double longitude;
	private double latitude;
	
	private Double velocity;
	private Double accuracy;
	
	private Date time;
	
	private String timeString;

	public Location(double latitude, double longitude, Double velocity,
			Double accuracy, Date time) {
		super();
		this.longitude = longitude;
		this.latitude = latitude;
		this.velocity = velocity;
		this.accuracy = accuracy;
		this.time = time;
		this.timeString = TIME_FORMAT.format(time);
	}

	public Location(double latitude, double longitude, Double velocity,
			Double accuracy, String timeString) {
		super();
		this.longitude = longitude;
		this.latitude = latitude;
		this.velocity = velocity;
		this.accuracy = accuracy;
		this.timeString = timeString;
		try {
			this.time = TIME_FORMAT.parse(timeString);
		} catch (ParseException e) {
			//won't happen
		}
	}

	public JSONObject toJSON() throws JSONException {
		JSONObject json = new JSONObject();
		json.put("latitude", latitude);
		json.put("longitude", longitude);
		json.put("time", timeString);
		if (velocity != null) {
			json.put("velocity", velocity);
		}
		if (accuracy != null) {
			json.put("accuracy", accuracy);
		}
		return json;
	}
	
	public static Location fromJSON(JSONObject json) throws JSONException {
		return new Location(json.getDouble("latitude"), json.getDouble("longitude"), 
				json.has("velocity") ? json.getDouble("velocity") : null, 
				json.has("accuracy") ? json.getDouble("accuracy") : null,
				json.getString("time"));
	}

	public double getLongitude() {
		return longitude;
	}

	public double getLatitude() {
		return latitude;
	}

	public Double getVelocity() {
		return velocity;
	}

	public Double getAccuracy() {
		return accuracy;
	}

	public Date getTime() {
		return time;
	}

	public String getTimeString() {
		return timeString;
	}
}
